/*
 * @Author: weidewei
 * @Date: 2025-11-19 15:39:51
 * @LastEditors: weidewei
 * @LastEditTime: 2025-11-24 09:43:12
 * @Description:
 * @FilePath: \2025-front-face\vite-react-ts-template\src\pages\useContext.tsx
 */
import styled from 'styled-components';
import React,{createContext} from 'react';
// 创建上下文
const ThemeContext = createContext<ThemeContextType>({} as ThemeContextType);
interface ThemeContextType {
  theme: string;
  setTheme: (theme: string) => void;
}
function Child() {
  // 获取上下文
  const themeContext = useContext(ThemeContext);
  const styles = {
    backgroundColor: themeContext.theme === 'light' ? 'white' : 'black',
    border: '1px solid red',
    width: 100 + 'px',
    height: 100 + 'px',
    color: themeContext.theme === 'light' ? 'black' : 'white'
  }
  return <div>
    <div style={styles}>
      child
    </div>
  </div>;
}
function Parent() {
  /* 
    useContext:  React 中用于在组件树中共享数据的 Hook
    入参：是 createContext 创建出来的对象
    返回值：返回传递的Context的值，并且是只读的。如果 context 发生变化，React 会自动重新渲染读取 context 的组件
  */
  const themeContext = useContext(ThemeContext);
  const styles = {
    backgroundColor: themeContext.theme === 'light' ? 'white' : 'black',
    border: '1px solid red',
    width: 100 + 'px',
    height: 100 + 'px',
    color: themeContext.theme === 'light' ? 'black' : 'white'
  }
  return (
    <div>
      <div style={styles}>
        Parent
        <button onClick={()=>themeContext.setTheme(themeContext.theme === 'light' ? 'dark' : 'light')}>切换主题</button>
      </div>
      <Child />
    </div>
  );
}

export default function useContextComp() {
  const [theme, setTheme] = useState('light');
  return (
    <Wrapper>
      <div className="use-context">
        <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>切换主题</button>
        <ThemeContext.Provider value={{theme,setTheme}}>
          <Parent />
        </ThemeContext.Provider>
      </div>
    </Wrapper>
  );
}
const Wrapper = styled.div`
  .use-context {
    color: #000;
  }
`;
